package com.iecg.controller.app;


import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.iecg.api.entity.IecgUser;
import com.iecg.api.entity.IecgUserDetail;
import com.iecg.api.entity.IecgUserEmergency;
import com.iecg.api.feign.RemoteWeixinService;
import com.iecg.filter.RequestHolder;
import com.iecg.service.IecgMobileService;
import com.iecg.service.IecgUserDetailService;
import com.iecg.service.IecgUserEmergencyService;
import com.iecg.service.IecgUserService;
import com.pig4cloud.pigx.common.core.constant.SecurityConstants;
import com.pig4cloud.pigx.common.core.util.R;
import com.pig4cloud.pigx.common.log.annotation.SysLog;
import com.pig4cloud.pigx.common.security.annotation.Inner;
import com.pig4cloud.pigx.common.security.service.PigxUser;
import com.pig4cloud.pigx.common.security.util.SecurityUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.util.List;
import java.util.UUID;

@RestController
@AllArgsConstructor
@RequestMapping("app/user" )
@Api(value = "app_user", tags = "App用户账号")
public class AppUserController {

	private final IecgUserService userService;

	private final IecgUserEmergencyService userEmergencyService;

	private final IecgUserDetailService userDetailService;

	private final IecgMobileService mobileService;

	private final RemoteWeixinService remoteWeixinService;

	/**
	 * 新增用户
	 * @param iecgUser 心电用户
	 * @return R
	 */
	@ApiOperation(value = "新用户注册", notes = "新用户注册")
	@SysLog("新用户注册" )
	@PostMapping
	public R save(@RequestBody IecgUser iecgUser) {
		    if(RequestHolder.getParam()== null){
		    	return R.failed("未验证手机验证码");
			}
			String mobile = RequestHolder.getParam();
		    iecgUser.setLockFlag("0");
		    iecgUser.setPhone(mobile);
		    iecgUser.setName(mobile);
		    IecgUser exsitUser = userService.getOne(Wrappers.<IecgUser>query().lambda().eq(IecgUser::getName, iecgUser.getName()));
		    if(exsitUser != null){
		    	return R.failed("用户名已注册");
			}
		   // exsitUser = userService.getOne(Wrappers.<IecgUser>query().lambda().eq(IecgUser::getOpenId, iecgUser.getOpenId()));
		   // if(exsitUser != null){
				userService.save(iecgUser);
			//}
			if(iecgUser.getIecgUserEmergencyList() != null && !iecgUser.getIecgUserEmergencyList().isEmpty()){
				userEmergencyService.saveBatch(iecgUser.getIecgUserEmergencyList());
			}
			if(iecgUser.getIecgUserDetail() !=null){
				IecgUserDetail iecgUserDetail = iecgUser.getIecgUserDetail();
				Long userId = iecgUser.getId();
				iecgUserDetail.setUserId(userId);
				userDetailService.save(iecgUserDetail);
			}
			return R.ok(iecgUser);
	}

	/**
	 * 忘记密码
	 * @param iecgUser
	 * @return
	 */
	@ApiOperation(value = "忘记密码", notes = "忘记密码")
	@SysLog("忘记密码" )
	@PutMapping(value = {"/password"})
	public R updateByPhone(@RequestBody IecgUser iecgUser) {
		String  mobile = RequestHolder.getParam();
		if(mobile == null){
			return R.failed("未验证手机验证码");
		}
		userService.update(iecgUser, Wrappers.<IecgUser>update().lambda().eq(IecgUser::getPhone, mobile));
		return R.ok();
	}


	/**
	 * 根据token获取当前用户全部信息
	 *
	 * @return 用户信息
	 */
	@GetMapping(value = {"/info"})
	public R info() {
		PigxUser pigxUser = SecurityUtils.getUser();
		String username = pigxUser.getUsername();
		IecgUser user = userService.getOne(Wrappers.<IecgUser>query()
				.lambda().eq(IecgUser::getName, username));
		if (user == null) {
			return R.failed(null, "获取当前用户信息失败");
		}
		return R.ok(user);
	}


	/**
	 * 根据用户名称获取当前用户全部信息
	 *
	 * @return 用户信息
	 */
	@ApiIgnore()
	@Inner
	@GetMapping(value = {"/info/{username}"})
	public R info(@PathVariable String username) {
		IecgUser user = userService.getOne(Wrappers.<IecgUser>query()
				.lambda().eq(IecgUser::getName, username));
		if (user == null) {
			return R.failed(null, "获取当前用户信息失败");
		}
		return R.ok(user);
	}

	/**
	 * 根据openId获取用户全部信息
	 * @param openId
	 * @return
	 */
	@ApiIgnore()
	@Inner
	@GetMapping(value = {"/info/openid/{openId}"})
	public R infoByOpenId(@PathVariable String openId) {
		IecgUser user = userService.getOne(Wrappers.<IecgUser>query()
				.lambda().eq(IecgUser::getOpenId, openId));
		if (user == null) {
			return R.failed(null, "获取当前用户信息失败");
		}
		return R.ok(user);
	}


	@ApiIgnore()
	@Inner
	@GetMapping(value = {"/info/social/{code}"})
	public R infoBySocial(@PathVariable String code) {
		R<String>  r = remoteWeixinService.getOpenId(code, SecurityConstants.FROM_IN);
		String openId = r.getData();
		if(openId == null){
			return R.failed();
		}
		IecgUser iecgUser = userService.getOne(Wrappers.<IecgUser>query()
				.lambda().eq(IecgUser::getOpenId, openId));
		if(iecgUser == null){
			iecgUser = new IecgUser();
			iecgUser.setOpenId(openId);
			iecgUser.setName(UUID.randomUUID().toString());
			iecgUser.setPassword("123456");
			iecgUser.setLockFlag("0");
			userService.save(iecgUser);
		}
		return R.ok(iecgUser);
	}

	/**
	 * 检查手机是否重复使用
	 * @param phone
	 * @return
	 */
	@GetMapping(value = {"/check/{phone}"})
	public R checkPhone(@PathVariable String phone) {
		List<IecgUser> userList = userService.list(Wrappers.<IecgUser>query()
				.lambda().eq(IecgUser::getPhone, phone));
		if (CollUtil.isEmpty(userList)) {
			return R.ok(Boolean.FALSE, "手机号未注册");
		}
		return R.ok(Boolean.TRUE, "手机号已注册");
	}


	/**
	 * 更新用户基本信息
	 * @param iecgUser
	 * @return
	 */
	@ApiOperation(value = "修改基本信息", notes = "修改基本信息")
	@SysLog("修改基本信息" )
	@PutMapping
	public R updateById(@RequestBody IecgUser iecgUser) {
		Long  userId = userService.getSecurityUser().getId();
		iecgUser.setId(userId);
		iecgUser.setAge(DateUtil.ageOfNow(iecgUser.getBirthday()));
		if(iecgUser.getIecgUserEmergencyList() != null && !iecgUser.getIecgUserEmergencyList().isEmpty()){
			List<IecgUserEmergency>  userEmergencyList = iecgUser.getIecgUserEmergencyList();
			return R.ok(userEmergencyService.saveOrUpdateBatch(userEmergencyList));
		}
		return R.ok(userService.updateById(iecgUser));
	}


	/**
	 * 获取手机验证码
	 * @param phone
	 * @return
	 */
	@GetMapping(value = {"/code/{phone}"})
	public R getSmsCode(@PathVariable String phone) {
		return mobileService.sendSmsCode(phone);
	}
}
